package net.apexes.commons.net;

import java.nio.charset.StandardCharsets;

/**
 * @author hedyn
 */
public class MulticastMonitorDemo {

    public static void main(String[] args) throws Exception {
        String host = "239.10.2.84";
        host = "FF02::10:2:84";
        int port = 10666;
        MulticastMonitor monitor1 = new MulticastMonitor(host, port);
        MulticastMonitor monitor2 = new MulticastMonitor(host, port);
        new Thread(() -> start(monitor1)).start();
        new Thread(() -> start(monitor2)).start();

        monitor1.sendMessage("1.第一条消息".getBytes(StandardCharsets.UTF_8));
        Thread.sleep(1000);
        monitor2.sendMessage("1.第二条消息".getBytes(StandardCharsets.UTF_8));
        Thread.sleep(2000);
        monitor1.sendMessage("2.第三条消息".getBytes(StandardCharsets.UTF_8));
        Thread.sleep(1000);
        monitor2.sendMessage("3.第四条消息".getBytes(StandardCharsets.UTF_8));
        Thread.sleep(1000);
        monitor1.sendMessage("bye".getBytes(StandardCharsets.UTF_8));
        Thread.sleep(2000);
        monitor1.close();
        monitor2.close();
    }

    private static final MulticastMonitor.Listener listener = MulticastMonitorDemo::onMessage;

    private static void start(MulticastMonitor monitor1) {
        monitor1.addListener(listener);
        try {
            monitor1.listen();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void onMessage(byte[] messageBytes) {
        String message = new String(messageBytes, StandardCharsets.UTF_8);
        System.out.println("<< " + message);
    }

}
